﻿using System.Collections.Generic;
using System.Linq;
using QuailServices.QuailDataServiceReference;

namespace QuailEnvironmentConfiguration
{
    public class Configuration
    {
        private Dictionary<string, string> _cache;
        private GetEnvironmentSettingResult[] _results;
        /// <summary>
        /// Initializes a new instance of the <see cref="Configuration"/> class.
        /// </summary>
        /// <param name="env">The env.</param>
        public Configuration(Environment env)
        {
            Env = env;
        }

        /// <summary>
        /// Gets the environment for this configuration item
        /// </summary>
        public Environment Env
        {
            get; private set;
        }

        /// <summary>
        /// Gets or sets a value indicating whether to enable caching settings from the database
        /// </summary>
        public bool EnableCache
        {
            get
            {
                return _cache != null;
            }

            set
            {
                if (value && _cache == null)
                    _cache = new Dictionary<string, string>();
                else if (!value && _cache != null)
                    _cache = null;
            }
        }

        /// <summary>
        /// Gets or sets the setting value by name
        /// </summary>
        /// <value>The value of the setting</value>
        public string this[string settingname]
        {
            get
            {
                string result;
                if (_cache != null && _cache.TryGetValue(settingname, out result))
                    return result;

                if (_results == null)
                {
                    using (var db = QuailServices.QuailDataServiceFactory.CreateClient())
                    {
                        _results = db.GetEnvironmentSettings(Env.EnvironmentId);
                    }
                }

                var row = _results
                    .Where(esr => string.Compare(esr.SettingName, settingname, true) == 0)
                    .FirstOrDefault();

                result = row == null ? null : row.SettingValue;

                if (_cache != null)
                    _cache[settingname] = result;

                return result;
            }

            set
            {
                using (var db = QuailServices.QuailDataServiceFactory.CreateClient())
                {
                    if (value == null)
                        db.DeleteEnvironmentSetting(Env.EnvironmentId, settingname);
                    else
                        db.SetEnvironmentSettingValue(Env.EnvironmentId, settingname, value);
                }

                if (_cache != null)
                    _cache[settingname] = value;
            }
        }
    }
}
